home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17154 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  56 lines

  1. Path: nntp1.best.com!usenet
  2. From: javaprog@best.com (John Lockwood)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Calling the wrong constructor
  5. Date: Sun, 14 Apr 1996 01:58:19 GMT
  6. Organization: Best Internet Communications
  7. Message-ID: <4kpm4c$jfe@nntp1.best.com>
  8. References: <4kot87$796@earth.njcc.com>
  9. NNTP-Posting-Host: javaprog.vip.best.com
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. mike@pluto.njcc.com (Michael Hohenshilt) wrote:
  13.  
  14. >  This might seem like a basic question, but lets say you something set u 
  15. >like the following:
  16.  
  17. >class Parent { Parent() { allocsomething} ~Parent() { deletesomething }... };
  18. >class Foo : Parent { Foo() { allocsomething } ~Foo() {deletesomething }... };
  19. >class Contain { Parent *ptr; ... };
  20.  
  21. >both parent, and foo allocate memory, and will free it up when being 
  22. >destructed.  Contain just holds a pointer of type Parent, and its 
  23. >constructor takes such a pointer as a parameter.
  24. >  If I store a pointer of type Foo into contain.ptr and discard that 
  25. >pointer.  Is there any way to have contain (via destructors) free up all 
  26. >memory allocated by Foo and/or Parent?
  27. >         Mike
  28.  
  29. The destructors need to be virtual.  
  30.  
  31. virtual ~Foo() { { /* ... */ }
  32. virtual ~Parent() { /* ... */ }
  33.  
  34. Then a base class pointer pointing to a derived class will do the
  35. right thing.  Note that the code as you've written it wouldn't
  36. do any base class allocation, since you didn't call your parent
  37. constructor.  
  38.  
  39. Bad programmer!  Just for that, no JOLT cola!  ;-)
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47. Regards,
  48.  
  49.  
  50.  
  51. John Lockwood
  52. john@wwg.com
  53. javaprog@best.com
  54. http://www.best.com/~javaprog
  55.  
  56.